from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-r^30rh6&auv+@j8%xkm=y#6d((ac=*+7&6ftai3_#6u1)7mu#z'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1', 'localhost', '0.0.0.0']

# CORS配置
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
    "http://127.0.0.1:5173",
    "http://localhost:5173",
    "http://127.0.0.1:3000",
    "http://localhost:3000",
]
CORS_ALLOWED_ORIGIN_REGEXES = [
    r"^http://127\.0\.0\.1:\d+$",
    r"^http://localhost:\d+$",
]
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

# Application definition

INSTALLED_APPS = [
    'haystack',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',
    'django_filters',
    "login.apps.LoginConfig",
    "order.apps.OrderConfig",
    "car.apps.CarConfig",
    "finance.apps.FinanceConfig",
    "ai.apps.AiConfig",
    "passeng.apps.PassengConfig",
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Didi.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Didi.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'di',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

STATIC_URL = "static/"
QINIU_ACCESS_KEY = '86mWt1ayRUK5lmD1TeQrnwdzraTjGGoEecbquTfp'
QINIU_SECRET_KEY = 'dcNdGGuFQTydYqz3MhBeXXugPSfe0UG39-dP1RfN'
QINIU_BUCKET_NAME = 'didiuser'
QINIU_BUCKET_DOMAIN = 'szwmnkd3g.hb-bkt.clouddn.com'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# 设置redis的配置
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/0',  # Redis 服务器地址和端口
        'OPTIONS': {
            'CLIENT_CLASS':
                'django_redis.client.DefaultClient',
            'IGNORE_EXCEPTIONS': True,  # 忽略异常
        }
    }, 'code': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',  # Redis 服务器地址和端口
        'OPTIONS': {
            'CLIENT_CLASS':
                'django_redis.client.DefaultClient',
            'IGNORE_EXCEPTIONS': True,  # 忽略异常
        }
    },
}

# 关于celery的配置
# Celery异步任务队列框架的配置项[注意：django的配置项必须大写，所以这里的所有配置项必须全部大写]
# 任务队列
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/14'
# 结果队列
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/15'
# 时区，与django的时区同步
CELERY_TIMEZONE = TIME_ZONE
# 防止死锁
CELERY_FORCE_EXECV = True
# 设置并发的worker数量
CELERYD_CONCURRENCY = 200
# 设置失败允许重试[这个慎用，如果失败任务无法再次执行成功，会产生指数级别的失败日志记录]
CELERY_ACKS_LATE = True
# 每个worker工作进程最多执行500个任务被销毁，可以防止内存泄漏，500是举例，根据自己的服务器的性能可以调整数值
CELERYD_MAX_TASKS_PER_CHILD = 500
# 单个任务的最大运行时间，超时会被杀死任务[慎用，有大文件操作、长时间上传、下载任务、图像分析时，需要关闭这个选项，或者设置更长时间]
CELERYD_TIME_LIMIT = 10 * 60
# 任务发出后，经过一段时间还未收到acknowledge, 就将任务重新交给其他worker执行
CELERY_DISABLE_RATE_LIMITS = True
# celery的任务结果内容格式[如果客户端调用程序不是python，则不能设置为pickle，因为其他语言不识别pickle格式数据]
CELERY_ACCEPT_CONTENT = ['json', 'pickle']
# haystack连接elasticsearch的配置信息
HAYSTACK_CONNECTIONS = {
    'default': {
        # haystack操作es的核心模块
        'ENGINE': 'haystack.backends.elasticsearch7_backend.Elasticsearch7SearchEngine',
        # es服务端地址
        'URL': 'http://114.55.65.49:9200/',
        # es索引仓库
        'INDEX_NAME': 'didi_knowledge_base',
    },
}

# 当mysqlORM操作数据库改变时，自动更新es的索引，否则es的索引会找不到新增的数据
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

# 支付宝配置
ALIPAY = {
    "appid": "9021000150672093",  # 支付宝应用ID，需要替换为真实的应用ID
    "app_private_key_path": BASE_DIR.parent / "keys/private.txt",  # 应用私钥文件路径
    "alipay_public_key_path": BASE_DIR.parent / "keys/public.txt",  # 支付宝公钥文件路径
    "notify_url": "http://127.0.0.1:8000/order/alipay/notify/",  # 异步通知地址
    "return_url": "http://127.0.0.1:5173/order/pay-result",  # 同步回调地址
    "gateway": "https://openapi-sandbox.dl.alipaydev.com/gateway.do",  # 支付宝网关（沙箱环境）
    "sign_type": "RSA2",  # 签名方式
    "debug": True,  # 沙箱模式
    "verbose": True,  # 输出调试信息，便于排查问题
    "timeout": 15,  # 请求超时时间
}

DINGTALK_APPID = 'ding1vc9mavivqifn3kh'
DINGTALK_APPSECRET = 'yhxvd0eLqgFpwyi2HLGmw6XlMl9pAwJj2gYo3PBVGhiGW_M45_iUag8pRfc3AwSy'

# 高德地图API配置
AMAP_API_KEY = 'e0f0a7123020ca7d2d854002371ca2f4'  # 高德地图Web服务API密钥

# MongoDB配置（阿里云MongoDB）
MONGODB_CONFIG = {
    'host': '114.55.65.49',  # 阿里云MongoDB地址
    'port': 27017,  # MongoDB端口
    'username': 'admin',  # MongoDB用户名
    'password': '123456',  # MongoDB密码
    'database': 'didi_comment_audit',  # 数据库名
    'auth_source': 'admin',  # 认证数据库
    'auth_mechanism': 'SCRAM-SHA-1',  # 认证机制
}

# 百度内容审核API配置
BAIDU_AUDIT_CONFIG = {
    'api_key': 'xQdnvD63bhbDruGmvEaURTy6',  # 百度API Key
    'secret_key': '9cAt0VAu9YvzymkiaEyQdeOHZi5nWnON',  # 百度Secret Key
    'access_token': '',  # 访问令牌（通过API Key和Secret Key获取）
    'text_audit_url': 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined',  # 文本审核接口
}

# LangChain配置（阿里云DashScope qwen-max模型）
LANGCHAIN_CONFIG = {
    'model_name': 'qwen-max',
    'api_key': 'sk-9679d8d27ecd400380c8b4ade7012b19',  # 请替换为您的DashScope API Key
    'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    'sensitive_words_file': r'D:\PY\car_user\Didi\order\sensitive_words.txt',  # 敏感词文件路径
    'max_length': 1000,
    'timeout': 30,
}

# Redis任务队列配置
REDIS_TASK_CONFIG = {
    'host': '127.0.0.1',
    'port': 6379,
    'db': 16,  # 使用不同的数据库避免冲突
    'password': None,
    'task_queue': 'comment_audit_tasks',  # 任务队列名称
    'result_queue': 'comment_audit_results',  # 结果队列名称
}
